from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View

# from myapp.models import User
import json
from django.core.serializers import serialize
from qiniu import Auth
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from mydjango.settings import BASE_DIR

# 导包
from django.db.models import Q, F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid
from myapp.models import User
import redis
import base64
from hashlib import sha256
import hmac
import urllib


def DingDingLogin(request):
    code = request.GET.get('code')
    t = time.time()
    # 时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret = 'kFeBIcAi-P5VNeA_2EIjARQu6dYct2h-3iiTUNpPEBuWjN3efumu2BfLhBgGVttz'
    # 构造签名
    signature = base64.b64encode(
        hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code': code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
        signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoaty1hbauyiitjsip2",
                        data=json.dumps(payload), headers=headers)

    res_dict = json.loads(res.text)
    user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
    dingding_id = ''
    user_id = ''
    if user:  # 判断该用户是否在本地库中创建过
        dingding_id = res_dict['user_info']['nick']
        user_id = user.id
    else:  # 没有创建过的用户，创建
        User.objects.create(username=str(res_dict['user_info']['nick']), password='')
        user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
        dingding_id = res_dict['user_info']['nick']
        user_id = user.id

    return redirect(
        'http://localhost:8080/?dingding_id=' + str(dingding_id) + '&' + 'uid=' + str(user_id))  # 重定向到主页 并且携带uid和钉钉的用户名


def make_password(password):
    md5 = hashlib.md5()  # 生成md5
    sign_str = str(password)  # 定义机密对象
    sign_utf8 = sign_str.encode(encoding='utf-8')  # 转码
    md5.update(sign_utf8)  # 加密
    md5_sever = md5.hexdigest()  # 生成密钥串

    return md5_sever


class NewRegisterAPIView(APIView):  # 用户注册接口
    def get(self, request):
        username = request.GET.get('username', '')  # 获取vue传过来的参数， 默认值为''
        password = request.GET.get('password', '')
        # print(username, password)
        user = User.objects.filter(username=username).first()  # 判断数据是否存在
        if user:
            return Response({
                'code': 405,
                'data': '用户已存在'
            })
        else:  # 用户名不存在， 创建该用户
            User.objects.create(username=username, password=make_password(password))
            return Response({
                'code': 200,
                'data': '用户创建成功'
            })


class NewLoginAPIview(APIView):  # 登陆接口
    def get(self, request):
        username = request.GET.get('username')  # 获取vue传过来的参数
        password = request.GET.get('password')
        user = User.objects.filter(username=username).first()  # 判断数据是否存在
        if user:
            if user.password == make_password(password):  # 判断用户密码和传过来的密码是否正确
                return Response({
                    'code': 200,
                    'data': '登陆成功'
                })
        # 用户名不存在 和 数据错误 都为 用户名或者密码错误
        return Response({
            'code': 405,
            'data': '用户名或者密码错误'
        })

# 定义密钥
class Qiniu(APIView):
    def get(self, request):
        q = Auth('UYGbfDgXLrBGi420P1TxxkegKFuN--NM3wEWymjK', 'kxDalUpo9-eclSfWT69xtuqdgdoQenjiOXZ3rzAQ')
        token = q.upload_token('uploadxiaobai')  # 指定上传空间
        # print(token)  # 打印一下返回值
        return Response({
            'code': 200,
            'token': token
        })
